use anyhow::Result;
// use teloxide::prelude::*;
use std::ops::Deref;
use uuid::Uuid;

use crate::helpers::{get_userpost_id, DatabaseConnection};
use matrix_sdk::{
    room::Joined,
    ruma::events::room::message::{
        OriginalSyncRoomMessageEvent, Relation, RoomMessageEventContent,
    },
    Client,
};
pub async fn favorite(
    ev: OriginalSyncRoomMessageEvent,
    _text: String,
    room: Joined,
    _client: Client,
    db: DatabaseConnection,
) -> Result<()> {
    let relation = ev.content.relates_to.unwrap();
    if let Relation::Reply { in_reply_to } = relation {
        let event_id = in_reply_to.event_id.to_string();
        if let Some(userpost_id) = get_userpost_id(event_id, &db).await? {
            log::info!("favoriting");
            favorite_post(userpost_id, &db).await.unwrap();
            let content = RoomMessageEventContent::text_markdown("now favorite");
            room.send(content, None).await.unwrap();
            log::info!("favorited post");
        }
    }
    Ok(())
}
async fn favorite_post(userpost_id: Uuid, db: &DatabaseConnection) -> Result<()> {
    db.lock()
        .await
        .deref()
        .query(
            "UPDATE userposts SET favorite = true WHERE id = $1",
            &[&userpost_id],
        )
        .await?;

    Ok(())
}
